<template>
  <div class="messages-container">
    <a-layout>
      <!-- 顶部标题栏 -->
      <a-layout-header class="header">
        <div class="header-content">
          <div class="header-left">
            <h2 class="page-title">
              <message-outlined />
              消息中心
            </h2>
          </div>
          <div class="header-right">
            <a-space>
              <a-button type="primary" @click="handleMarkAllRead" class="action-btn">
                <template #icon><check-outlined /></template>
                <span class="btn-text">全部已读</span>
              </a-button>
              <a-popconfirm
                title="确定要清空所有消息吗？"
                @confirm="handleClearAll"
                ok-text="确定"
                cancel-text="取消"
              >
                <a-button class="action-btn">
                  <template #icon><delete-outlined /></template>
                  <span class="btn-text">清空消息</span>
                </a-button>
              </a-popconfirm>
            </a-space>
          </div>
        </div>
      </a-layout-header>

      <a-layout-content class="content">
        <a-row :gutter="{ xs: 8, sm: 16, md: 24 }">
          <!-- 左侧分类菜单 -->
          <a-col :xs="24" :sm="8" :md="6" :lg="5" class="category-col">
            <div class="category-card hover-shadow">
              <a-menu
                v-model:selectedKeys="selectedKeys"
                mode="inline"
                class="category-menu"
              >
                <a-menu-item key="all" class="menu-item">
                  <template #icon><inbox-outlined class="menu-icon" /></template>
                  <span class="menu-text">全部消息</span>
                  <a-badge :count="messageStats.total" class="menu-badge" />
                </a-menu-item>
                <a-menu-item key="unread" class="menu-item">
                  <template #icon><bell-outlined class="menu-icon" /></template>
                  <span class="menu-text">未读消息</span>
                  <a-badge :count="messageStats.unread" class="menu-badge" />
                </a-menu-item>
                <a-menu-divider />
                <a-menu-item key="system" class="menu-item">
                  <template #icon><notification-outlined class="menu-icon system" /></template>
                  <span class="menu-text">系统通知</span>
                  <a-badge :count="messageStats.system" class="menu-badge" />
                </a-menu-item>
                <a-menu-item key="reply" class="menu-item">
                  <template #icon><comment-outlined class="menu-icon reply" /></template>
                  <span class="menu-text">评论回复</span>
                  <a-badge :count="messageStats.reply" class="menu-badge" />
                </a-menu-item>
                <a-menu-item key="like" class="menu-item">
                  <template #icon><like-outlined class="menu-icon like" /></template>
                  <span class="menu-text">收到的赞</span>
                  <a-badge :count="messageStats.like" class="menu-badge" />
                </a-menu-item>
                <a-menu-item key="mention" class="menu-item">
                  <template #icon><user-outlined class="menu-icon mention" /></template>
                  <span class="menu-text">@提及我</span>
                  <a-badge :count="messageStats.mention" class="menu-badge" />
                </a-menu-item>
              </a-menu>
            </div>
          </a-col>

          <!-- 右侧消息列表 -->
          <a-col :xs="24" :sm="16" :md="18" :lg="19" class="message-col">
            <div class="message-list-card hover-shadow">
              <a-spin :spinning="messageStore.loading">
                <a-list
                  :data-source="filteredMessages"
                  :pagination="pagination"
                  class="message-list"
                >
                  <template #renderItem="{ item }">
                    <a-list-item :class="['message-item', { 'unread': !item.isRead }]">
                      <a-list-item-meta class="message-meta">
                        <template #avatar>
                          <div class="message-icon-wrapper">
                            <a-avatar :class="['message-icon', getIconClass(item.type)]">
                              <template #icon>
                                <component :is="getMessageIcon(item.type)" />
                              </template>
                            </a-avatar>
                          </div>
                        </template>
                        <template #title>
                          <div class="message-header">
                            <span class="message-title">{{ item.title }}</span>
                            <a-tag 
                              v-if="!item.isRead" 
                              class="unread-tag"
                            >
                              未读
                            </a-tag>
                          </div>
                        </template>
                        <template #description>
                          <div class="message-content">
                            <p class="message-text">{{ item.content }}</p>
                            <div class="message-footer">
                              <span class="message-time">{{ item.time }}</span>
                              <div class="message-actions">
                                <a-button 
                                  type="link" 
                                  v-if="!item.isRead"
                                  @click="handleMarkRead(item)"
                                  class="action-link"
                                >
                                  <template #icon><check-outlined /></template>
                                  标记已读
                                </a-button>
                                <a-button 
                                  type="link" 
                                  v-if="item.link || item.resourceId"
                                  @click="openDetail(item)"
                                  class="action-link"
                                >
                                  <template #icon><eye-outlined /></template>
                                  查看详情
                                </a-button>
                                <a-popconfirm
                                  title="确定要删除这条消息吗？"
                                  @confirm="handleDelete(item)"
                                  ok-text="确定"
                                  cancel-text="取消"
                                >
                                  <a-button type="link" danger class="action-link">
                                    <template #icon><delete-outlined /></template>
                                    删除
                                  </a-button>
                                </a-popconfirm>
                              </div>
                            </div>
                          </div>
                        </template>
                      </a-list-item-meta>
                    </a-list-item>
                  </template>
                  
                  <!-- 空状态 -->
                  <template #empty>
                    <div class="empty-state">
                      <inbox-outlined class="empty-icon" />
                      <p class="empty-text">暂无消息</p>
                    </div>
                  </template>
                </a-list>
              </a-spin>
            </div>
          </a-col>
        </a-row>
      </a-layout-content>
    </a-layout>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useMessageStore } from '@/stores/message'
import { useUserStore } from '@/stores/user'
import { message } from 'ant-design-vue'
import {
  InboxOutlined,
  BellOutlined,
  NotificationOutlined,
  CommentOutlined,
  LikeOutlined,
  CheckOutlined,
  DeleteOutlined,
  MessageOutlined,
  EyeOutlined,
  UserOutlined
} from '@ant-design/icons-vue'

const router = useRouter()
const messageStore = useMessageStore()
const userStore = useUserStore()
const loading = ref(false)
const selectedKeys = ref(['all'])

// 获取消息列表
onMounted(async () => {
  if (!userStore.isLoggedIn) {
    message.warning('请先登录')
    router.push('/login')
    return
  }
  
  loading.value = true
  try {
    await messageStore.fetchMessages()
  } catch (error) {
    console.error('获取消息列表失败:', error)
    message.error('获取消息失败，请刷新重试')
  } finally {
    loading.value = false
  }
})

// 消息类型映射
const messageTypeMapping = {
  'POST_AUDIT_APPROVED': 'system',
  'POST_AUDIT_REJECTED': 'system',
  'POST_LIKE': 'like',
  'COMMENT_CREATE': 'reply',
  'COMMENT_REPLY': 'reply',
  'USER_MENTION': 'mention',
  'SYSTEM_NOTIFICATION': 'system'
}

// 消息统计
const messageStats = computed(() => {
  const msgs = messageStore.messages
  return {
    total: msgs.length,
    unread: msgs.filter(msg => !msg.isRead).length,
    system: msgs.filter(msg => ['POST_AUDIT_APPROVED', 'POST_AUDIT_REJECTED', 'SYSTEM_NOTIFICATION'].includes(msg.type)).length,
    reply: msgs.filter(msg => ['COMMENT_CREATE', 'COMMENT_REPLY'].includes(msg.type)).length,
    like: msgs.filter(msg => msg.type === 'POST_LIKE').length,
    mention: msgs.filter(msg => msg.type === 'USER_MENTION').length
  }
})

// 消息过滤
const filteredMessages = computed(() => {
  const msgs = messageStore.messages
  switch (selectedKeys.value[0]) {
    case 'unread':
      return msgs.filter(msg => !msg.isRead)
    case 'system':
      return msgs.filter(msg => ['POST_AUDIT_APPROVED', 'POST_AUDIT_REJECTED', 'SYSTEM_NOTIFICATION'].includes(msg.type))
    case 'reply':
      return msgs.filter(msg => ['COMMENT_CREATE', 'COMMENT_REPLY'].includes(msg.type))
    case 'like':
      return msgs.filter(msg => msg.type === 'POST_LIKE')
    case 'mention':
      return msgs.filter(msg => msg.type === 'USER_MENTION')
    default:
      return msgs
  }
})

// 监听选中的菜单项变化
watch(selectedKeys, (newVal) => {
  if (newVal[0] !== 'all') {
    // 当用户选择特定类型消息时，如果需要可以重新加载该类型的消息
    // 例如当选择未读消息时，刷新未读消息列表
    if (newVal[0] === 'unread') {
      messageStore.fetchMessages(false) // 获取未读消息
    }
  }
})

// 分页配置
const pagination = {
  pageSize: 10,
  showQuickJumper: true,
  showSizeChanger: true,
  pageSizeOptions: ['5', '10', '20', '50'],
  showTotal: total => `共 ${total} 条消息`
}

// 标记消息已读
const handleMarkRead = async (item) => {
  loading.value = true
  try {
    const success = await messageStore.markAsRead(item.id)
    if (success) {
      message.success('已标记为已读')
    } else {
      message.error('操作失败')
    }
  } catch (error) {
    console.error('标记已读失败:', error)
    message.error('操作失败，请重试')
  } finally {
    loading.value = false
  }
}

// 标记所有消息已读
const handleMarkAllRead = async () => {
  loading.value = true
  try {
    // 如果当前选择了特定类型，则只标记该类型的消息为已读
    const type = selectedKeys.value[0] === 'all' ? undefined : 
                (selectedKeys.value[0] === 'system' ? 'POST_AUDIT' : 
                 selectedKeys.value[0] === 'reply' ? 'COMMENT' : 
                 selectedKeys.value[0] === 'like' ? 'POST_LIKE' : 
                 selectedKeys.value[0] === 'mention' ? 'USER_MENTION' : undefined)
    
    const success = await messageStore.markAllAsRead(type)
    if (success) {
      message.success('已全部标记为已读')
      // 重新加载消息
      await messageStore.fetchMessages()
    } else {
      message.error('操作失败')
    }
  } catch (error) {
    console.error('标记全部已读失败:', error)
    message.error('操作失败，请重试')
  } finally {
    loading.value = false
  }
}

// 删除消息
const handleDelete = async (item) => {
  loading.value = true
  try {
    const success = await messageStore.deleteMessage(item.id)
    if (success) {
      message.success('删除成功')
    } else {
      message.error('删除失败')
    }
  } catch (error) {
    console.error('删除消息失败:', error)
    message.error('删除失败，请重试')
  } finally {
    loading.value = false
  }
}

// 清空所有消息
const handleClearAll = async () => {
  loading.value = true
  try {
    const success = await messageStore.clearAllMessages()
    if (success) {
      message.success('已清空所有消息')
    } else {
      message.error('操作失败')
    }
  } catch (error) {
    console.error('清空消息失败:', error)
    message.error('操作失败，请重试')
  } finally {
    loading.value = false
  }
}

// 获取消息图标
const getMessageIcon = (type) => {
  switch (type) {
    case 'POST_AUDIT_APPROVED':
    case 'POST_AUDIT_REJECTED':
    case 'SYSTEM_NOTIFICATION':
      return NotificationOutlined
    case 'COMMENT_CREATE':
    case 'COMMENT_REPLY':
      return CommentOutlined
    case 'POST_LIKE':
      return LikeOutlined
    case 'USER_MENTION':
      return UserOutlined
    default:
      return MessageOutlined
  }
}

// 获取消息图标类名
const getIconClass = (type) => {
  switch (type) {
    case 'POST_AUDIT_APPROVED':
    case 'POST_AUDIT_REJECTED':
    case 'SYSTEM_NOTIFICATION':
      return 'system'
    case 'COMMENT_CREATE':
    case 'COMMENT_REPLY':
      return 'reply'
    case 'POST_LIKE':
      return 'like'
    case 'USER_MENTION':
      return 'mention'
    default:
      return ''
  }
}

// 打开详情页面
const openDetail = (item) => {
  if (item.link) {
    // 使用路由导航
    router.push(item.link)
  } else if (item.resourceId && item.resourceType === 'POST') {
    router.push(`/post/${item.resourceId}`)
  } else if (item.resourceId && item.resourceType === 'COMMENT') {
    // 如果是评论类消息，跳转到对应的帖子评论位置
    // 需要先获取帖子ID
    const postId = item.link?.match(/\/post\/(\d+)/)?.[1]
    if (postId) {
      router.push(`/post/${postId}#comment-${item.resourceId}`)
    }
  }
}
</script>

<style lang="scss" scoped>
.messages-container {
  min-height: calc(100vh - 64px);
  background: #f5f7fa;
  width: 100%;

  .header {
    background: #fff;
    padding: 0;
    position: sticky;
    top: 0;
    z-index: 100;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);

    .header-content {
      max-width: 1400px;
      margin: 0 auto;
      padding: 0 24px;
      height: 64px;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .header-left {
        .page-title {
          margin: 0;
          font-size: 20px;
          font-weight: 600;
          display: flex;
          align-items: center;
          gap: 12px;
          background: linear-gradient(45deg, #1890ff, #40a9ff);
          -webkit-background-clip: text;
          color: transparent;

          .anticon {
            font-size: 24px;
            background: linear-gradient(45deg, #1890ff, #40a9ff);
            -webkit-background-clip: text;
            color: transparent;
          }
        }
      }

      .action-btn {
        height: 36px;
        border-radius: 8px;
        padding: 0 16px;
        display: flex;
        align-items: center;
        gap: 8px;
        transition: all 0.3s ease;

        &:hover {
          transform: translateY(-2px);
        }

        &.ant-btn-primary {
          background: linear-gradient(45deg, #1890ff, #40a9ff);
          border: none;
          box-shadow: 0 2px 8px rgba(24, 144, 255, 0.35);

          &:hover {
            box-shadow: 0 4px 12px rgba(24, 144, 255, 0.45);
          }
        }
      }
    }
  }

  .content {
    max-width: 1400px;
    margin: 24px auto;
    padding: 0 24px;
    width: 100%;

    .category-col {
      margin-bottom: 16px;
    }

    .category-card {
      background: #fff;
      border-radius: 12px;
      padding: 12px;
      transition: all 0.3s ease;
      width: 100%;

      .category-menu {
        border: none;
        background: transparent;
        width: 100%;

        :deep(.ant-menu-item) {
          margin: 4px 0;
          padding: 0 16px;
          border-radius: 8px;
          height: 44px;
          line-height: 44px;
          transition: all 0.3s ease;
          width: 100%;
          position: relative;
          background: transparent;

          .menu-text {
            display: inline-block;
            margin-right: 32px;
            font-size: 14px;
            color: #595959;
          }

          .menu-badge {
            position: absolute;
            right: 16px;
            top: 50%;
            transform: translateY(-50%);

            :deep(.ant-badge-count) {
              min-width: 16px;
              height: 16px;
              line-height: 16px;
              padding: 0 4px;
              border-radius: 8px;
              font-size: 12px;
              font-weight: normal;
              box-shadow: none;
              background: #ff4d4f;
              border: 2px solid #fff;
            }
          }

          .menu-icon {
            font-size: 18px;
            margin-right: 12px;
            width: 18px;
            display: inline-block;
            text-align: center;
            vertical-align: -0.125em;

            &.system { 
              color: #1890ff; 
            }
            &.reply { 
              color: #52c41a; 
            }
            &.like { 
              color: #ff4d4f; 
            }
            &.mention { 
              color: #faad14; 
            }
          }

          &:hover {
            color: #1890ff;
            background: rgba(24, 144, 255, 0.1);
          }

          &.ant-menu-item-selected {
            background: #e6f7ff;
            color: #1890ff;
            font-weight: 500;

            .menu-text {
              color: #1890ff;
            }

            .menu-badge {
              :deep(.ant-badge-count) {
                background: #1890ff;
                border-color: #e6f7ff;
              }
            }

            &::after {
              display: none;
            }
          }

          &::after {
            display: none;
          }
        }

        :deep(.ant-menu-item-divider) {
          margin: 8px 0;
          background-color: #f0f0f0;
        }
      }
    }

    .message-list-card {
      background: #fff;
      border-radius: 12px;
      padding: 24px;
      min-height: 600px;
      width: 100%;

      .message-list {
        .message-item {
          padding: 16px 24px;
          border-radius: 8px;
          margin-bottom: 16px;
          border: 1px solid #f0f0f0;
          transition: all 0.3s ease;
          width: 100%;

          &:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
            border-color: transparent;

            .message-actions {
              opacity: 1;
              transform: translateX(0);
            }
          }

          &.unread {
            background: rgba(24, 144, 255, 0.05);
            border-color: rgba(24, 144, 255, 0.1);

            &::before {
              content: '';
              position: absolute;
              left: 0;
              top: 0;
              height: 100%;
              width: 4px;
              background: linear-gradient(to bottom, #1890ff, #40a9ff);
              border-radius: 2px;
            }
          }

          .message-meta {
            width: 100%;
            
            .message-icon-wrapper {
              .message-icon {
                width: 40px;
                height: 40px;
                border-radius: 20px;
                font-size: 20px;
                display: flex;
                align-items: center;
                justify-content: center;
                transition: all 0.3s ease;

                &.system { 
                  background: #e6f7ff; 
                  color: #1890ff;
                }
                &.reply { 
                  background: #f6ffed; 
                  color: #52c41a;
                }
                &.like { 
                  background: #fff1f0; 
                  color: #f5222d;
                }
                &.mention { 
                  background: #faad14; 
                  color: #fff;
                }

                &:hover {
                  transform: scale(1.1);
                }
              }
            }

            .message-header {
              display: flex;
              align-items: center;
              gap: 12px;
              flex-wrap: wrap;

              .message-title {
                font-size: 16px;
                font-weight: 500;
                color: #262626;
              }

              .unread-tag {
                background: rgba(24, 144, 255, 0.1);
                color: #1890ff;
                border: none;
                border-radius: 4px;
                padding: 2px 8px;
                font-size: 12px;
              }
            }

            .message-content {
              .message-text {
                color: #595959;
                margin: 8px 0;
                line-height: 1.6;
                word-break: break-word;
              }

              .message-footer {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin-top: 12px;
                flex-wrap: wrap;
                gap: 8px;

                .message-time {
                  color: #8c8c8c;
                  font-size: 13px;
                }

                .message-actions {
                  display: flex;
                  gap: 16px;
                  opacity: 0;
                  transform: translateX(10px);
                  transition: all 0.3s ease;
                  flex-wrap: wrap;

                  .action-link {
                    padding: 4px 8px;
                    height: auto;
                    font-size: 13px;
                    display: flex;
                    align-items: center;
                    gap: 4px;

                    .anticon {
                      font-size: 14px;
                    }

                    &:hover {
                      background: rgba(0, 0, 0, 0.02);
                      border-radius: 4px;
                    }

                    &.ant-btn-dangerous {
                      color: #ff4d4f;
                      &:hover {
                        background: rgba(255, 77, 79, 0.1);
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }

      .empty-state {
        padding: 48px 0;
        text-align: center;
        color: #8c8c8c;

        .empty-icon {
          font-size: 48px;
          margin-bottom: 16px;
          color: #bfbfbf;
        }

        .empty-text {
          font-size: 14px;
          margin: 0;
        }
      }
    }
  }
}

// 添加响应式样式
@media screen and (max-width: 1200px) {
  .messages-container {
    .content {
      padding: 0 16px;
    }
  }
}

@media screen and (max-width: 768px) {
  .messages-container {
    .header {
      .header-content {
        padding: 0 16px;

        .page-title {
          font-size: 18px;
        }

        .action-btn {
          padding: 0 12px;
          
          .btn-text {
            display: none;
          }
        }
      }
    }

    .content {
      padding: 0 12px;
      margin: 16px auto;

      .message-list-card {
        padding: 16px 12px;

        .message-item {
          padding: 12px;

          .message-meta {
            .message-icon {
              width: 32px;
              height: 32px;
              font-size: 16px;
            }

            .message-title {
              font-size: 14px;
            }

            .message-content {
              .message-footer {
                flex-direction: column;
                align-items: flex-start;
                gap: 8px;

                .message-actions {
                  opacity: 1;
                  transform: none;
                  width: 100%;
                  justify-content: space-between;
                }
              }
            }
          }
        }
      }
    }
  }
}

// 添加平板响应式样式
@media screen and (min-width: 769px) and (max-width: 992px) {
  .messages-container {
    .content {
      .message-list-card {
        .message-item {
          .message-meta {
            .message-content {
              .message-footer {
                .message-actions {
                  opacity: 1;
                  transform: none;
                }
              }
            }
          }
        }
      }
    }
  }
}

// 添加悬浮效果
.hover-shadow {
  transition: box-shadow 0.3s ease, transform 0.3s ease;
  
  &:hover {
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08);
  }
}
</style> 